package com.yc.service;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;


import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import dev.langchain4j.community.model.dashscope.QwenEmbeddingModel;
import dev.langchain4j.community.store.embedding.clickhouse.ClickHouseEmbeddingStore;
import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.store.embedding.EmbeddingSearchRequest;
import dev.langchain4j.store.embedding.EmbeddingSearchResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ToolServices {

    @Autowired
    @Qualifier("excelEmbeddingStore")  // 如果你的成绩向量存储在 excel_embeddings 表中
    private ClickHouseEmbeddingStore scoreEmbeddingStore;
    @Autowired
    private QwenEmbeddingModel embeddingModel;


    // 添加 setter 方法
    public void setScoreEmbeddingStore(ClickHouseEmbeddingStore scoreEmbeddingStore) {
        this.scoreEmbeddingStore = scoreEmbeddingStore;
    }
    @Tool("学生查分工具。用户提供学号、姓名或班级信息，返回该学生的成绩与解释")
    public String queryScoreByVector(@P("用户输入") String userQuery) {

        try {

            // 1. 生成查询向量
            Embedding embedding = embeddingModel.embed(userQuery).content();
            // 2. 向量检索（匹配前1条）
            EmbeddingSearchResult<TextSegment> result = scoreEmbeddingStore.search(EmbeddingSearchRequest.builder()
                    .queryEmbedding(Embedding.from(embedding.vector()))
                    .maxResults(1)
                    .minScore(0.7)
                    .build());
            // 3. 返回匹配内容
            List<TextSegment> matches = result.matches().stream()
                    .map(match -> match.embedded())
                    .collect(Collectors.toList());
            if (matches.isEmpty()) {
                return "未找到与该学生相关的成绩信息，请确认学号或姓名。";
            }
            System.out.println("matches = " + matches);
            return matches.get(0).text();  // 返回原始文本结果（如：成绩 + 解释）
        } catch (Exception e) {
            e.printStackTrace();
            return "查询成绩失败：" + e.getMessage();
        }
    }
    @Tool("求多个数的和")
    public int add(int...nums) {
        int total = 0;
        for (int num : nums) {
            total += num;
        }
        System.out.println("total = " + total);
        return total;
    }
    @Tool("求一个字符串的长度")
    public int length(String str) {
        System.out.println("length = " + str.length());
        return str.length();
    }
    @Tool("计算一个数的平方根")
    public double sqrt(double num) {
        System.out.println("sqrt = " + Math.sqrt(num));
        return Math.sqrt(num);
    }
    // 温度单位的枚举类
    public enum TemperatureUnit {
        CELSIUS, FAHRENHEIT, KELVIN
    }
    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class WeatherResponse {
        @JsonProperty("results")
        public List<WeatherData> results;

        @JsonIgnoreProperties(ignoreUnknown = true)
        public static class WeatherData {
            @JsonProperty("location")
            @JsonIgnoreProperties(ignoreUnknown = true)
            public Location location;
            @JsonProperty("now")
            @JsonIgnoreProperties(ignoreUnknown = true)
            public Now now;
            @JsonIgnoreProperties(ignoreUnknown = true)
            public static class Location {
                @JsonProperty("name")
                public String name;
                // 其他字段会被自动忽略
            }

            @JsonIgnoreProperties(ignoreUnknown = true)
            public static class Now {
                @JsonProperty("text")
                public String text;
                @JsonProperty("temperature")
                public String temperature;
                @JsonProperty("code")  // 新增code字段
                public String code;  // 虽然不使用但需要定义
            }
        }
    }

    @Tool("用户会询问某个城市的天气,他还会给你温度单位，请返回城市的天气情况")
    public String getWeather(
            @P("城市名称") String city,
            @P("温度单位") TemperatureUnit unit
    ) {
        try {
            String apiKey = "SlUbsQwIT-x7oPyEC";
            String url = String.format(
                    "https://api.seniverse.com/v3/weather/now.json?key=%s&location=%s&language=zh-Hans&unit=c",
                    apiKey, URLEncoder.encode(city, "UTF-8")
            );

            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .timeout(Duration.ofSeconds(10))
                    .build();
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            String json = response.body();

            ObjectMapper mapper = new ObjectMapper();
            WeatherResponse weatherResponse = mapper.readValue(json, WeatherResponse.class);

            WeatherResponse.WeatherData.Now now = weatherResponse.results.get(0).now;
            return String.format("%s的天气：%s，气温 %s°C", city, now.text, now.temperature);
        } catch (Exception e) {
            e.printStackTrace();
            return "获取天气失败：" + e.getMessage();
        }
    }

}
